<template>
  <div class="page-modal">
    <el-dialog
      v-model="dialogVisible"
      :title="modalConfig.new_editName"
      width="25%"
      destroy-on-close
      center
    >
      <LylForm v-bind="modalConfig" v-model="formData" />
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleConfirmClick"
            :disabled="modalConfig.confirmDisable"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import LylForm from '@/base-ui/form/src/form.vue'
import store from '@/store'
import { ref, defineProps, defineExpose, watch } from 'vue'
const props = defineProps({
  modalConfig: {
    type: Object,
    default: () => ({})
  },
  defaultInfo: {
    type: Object,
    default: () => ({})
  },
  pageName: {
    type: String,
    default: ''
  },
  otherInfo: {
    type: Object,
    default: () => ({})
  }
})

const dialogVisible = ref(false)
const formData = ref<any>({})

const handleConfirmClick = () => {
  dialogVisible.value = false

  if (Object.keys(props.defaultInfo).length) {
    // 有数据代表编辑
    store.dispatch('system/editPageDataAction', {
      pageName: props.pageName,
      editData: { ...formData.value, ...props.otherInfo },
      id: props.defaultInfo.id
    })
  } else {
    // 此处代表新建
    store.dispatch('system/createPageDataAction', {
      pageName: props.pageName,
      newData: { ...formData.value, ...props.otherInfo }
    })
  }
}

watch(
  () => props.defaultInfo,
  (newValue) => {
    for (const item of props.modalConfig.formItems) {
      formData.value[`${item.field}`] = newValue[`${item.field}`]
    }
  }
)
/**
 * 暴露本组件中中的属性方法2，以供父组件使用ref获取得到
 */
defineExpose({ dialogVisible })
</script>

<style scoped></style>
